package com.webamc.validator;

import com.webamc.model.Result;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by Prash.
 * User: Choti
 * Date: Apr 3, 2009
 * Time: 11:55:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class ParamValidator extends AbstractValidator {
    private Logger log = Logger.getLogger(ParamValidator.class);
    private Map<String, Pattern> rules = new HashMap<String, Pattern>();
    private Map<String, String> params = new HashMap<String, String>();

    public void setRules(Map<String, String> map) {
        for (Map.Entry<String, String> o : map.entrySet()) {
            this.rules.put(o.getKey(), Pattern.compile(o.getValue()));
        }
    }

    public void setParams(Map<String, String> map) {
        this.params = map;
    }

    public Result validate(Map<String, String[]> map) {
        Result r = null;
        for (Map.Entry<String, String[]> o : map.entrySet()) {
            String ruleKey = params.get(o.getKey());
            if (ruleKey != null) { //rule exists to validate this parameter
                Pattern p = rules.get(ruleKey);
                if (p != null) { //just playing safe, null means configuration is wrong!!
                    for (String s : o.getValue()) {
                        if (!p.matcher(s).matches()) {
                            log.debug("Failed: Parameter=" + o.getKey() + ", Value='" + s + "', Rule='" + ruleKey + "', Pattern='" + p.pattern() + "'");
                            if (null == r) {
                                r = new Result();
                            }
                            r.setPassed(false);
                            r.addMsg("Invalid Value - Parameter: [" + o.getKey() + "], Value: [" + s + "]");
                            break; //todo:outer?
                        }
                    }
                }
            }
        }

        return r;
    }
}
